/*******************************************************************************
 * Package: com.song.boot.springstudy.task
 * Type:    PoolTask
 * Date:    2022-07-09 17:11
 *
 * Copyright (c) 2022 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.boot.springstudy.thread.task;

import org.springframework.util.StopWatch;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * 功能描述：Future.get()用于异步结果的获取。它是阻塞的，背后原理是什么呢？
 * 异步。效率有多快
 * FutureTask 配合线程池使用
 * @author Songxianyang
 * @date 2022-07-09 17:11
 */
public class PoolTask {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        //Executors.newSingleThreadExecutor();
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        Service1 service1 = new Service1();
        StopWatch watch = new StopWatch();
        watch.start();
        service1.testUser1();
        
        //service1.testUser2();
        //int i = service1.testUserInt(1);
        //System.out.println(i);
        
        //FutureTask futureTask1 = new FutureTask<Object>(new Callable<Object>() {
        //    @Override
        //    public Object call() throws Exception {
        //        service1.testUser2();
        //        return null;
        //    }
        //});
        //executorService.submit(futureTask1);


        FutureTask<Integer> futureTask = new FutureTask<>((Callable<Integer>) () -> service1.testUserInt(99));
        executorService.submit(futureTask);
        //
        Integer integer = futureTask.get();
        System.out.println(integer);
        executorService.shutdown();
        
        watch.stop();
        
        System.out.println("耗时：" + watch.prettyPrint());
        
    }
}
class Service1 {
    public void testUser1() throws InterruptedException {
        Thread.sleep(4000);
        System.out.println("执行方法1");
    }
    public void testUser2() throws InterruptedException {
        Thread.sleep(4000);
        System.out.println("执行方法2"+Thread.currentThread().getName());
    }
    public int testUserInt(int i) throws InterruptedException {
        Thread.sleep(8000);
        System.out.println("执行方法int返回值"+Thread.currentThread().getName());
        return i;
    }
}